# -*- coding:utf-8 -*-
# 自动生成一个能代理 7070 端口的批处理
# 使用了一个免费的帐号，但是这个帐号每周会变
# 作者：mushroom
# E-Mail : linzhanyu@gmail.com

from make_cmd   import *
from analyzer   import *
from spider     import *

import platform
import os
import stat

# import urllib2
# import re
# 
file_name = 'test.html'

system_type = platform.system()
if system_type == 'Windows':
    script_name = 'FreeSSH.cmd'
elif system_type == 'Linux':
    script_name = 'freessh.sh'
# ssh_bin = 'F:\\TDDOWNLOAD\\Software\\putty\\plink.EXE'
# 
# refresh_url = 1
# if refresh_url:
#     url = 'http://xinm.tk/free.html'
#     request = urllib2.urlopen( url )
#     content = request.read().decode('utf-8')
#     # print content
#     f = open(file_name, 'w')
#     f.write( content.encode('utf-8') )
#     f.flush()
#     f.close()
# else:
#     f = open(file_name, 'r')
#     content = f.read().decode('utf-8')
#     f.close()
# 
# # regex = re.compile('<p>([^<]*)<[^/]+/>([^<]*)<[^/]+/>([^<]*)<[^/]+/>')
# regex = re.compile(u'[：:]\s*([^</"]{8,})', re.UNICODE)
# tag_beg = '<p>'
# tag_end = '</p>'
# result = []
# idx_beg = content.find(tag_beg)
# while idx_beg != -1 :
#     idx_end = content.find(tag_end, idx_beg)
#     sub_content = content[idx_beg+len(tag_beg):idx_end]
#     # print sub_content
#     findRet = regex.findall( sub_content )
#     if len(findRet) != 0 :
#         for item in findRet :
#             result.append( item )
#         # print idx_beg, idx_end, '\n', content[idx_beg+len(tag_beg):idx_end]
#     idx_beg = content.find(tag_beg, idx_end)
# 
# command = '%%PUTTY%% -v -C -N -D 127.0.0.1:7070 -l %s -pw %s -P 22 %s'
# f = open('FREESSH.CMD', 'w')
# lines = []
# lines.append( '@ECHO OFF' )
# lines.append( 'SET PUTTY=%s\n'%(ssh_bin) )
# lines.append( ':START' )
# for i in range( len(result)/3 ):
#     idx_beg = i*3
#     idx_end = idx_beg + 3
#     g = result[idx_beg:idx_end]
#     print command % (g[1], g[2], g[0])
#     lines.append( command % (g[1],g[2],g[0]) )
# lines.append( 'ECHO %%ERRORLEVEL%%' )
# lines.append( 'GOTO START' )
# for line in lines:
#     f.write( '%s\n'% (line) )
# f.flush()
# f.close()

if __name__ == '__main__' :
    print '*' * 50
    spider = WebSpider()
    f = open( script_name, 'w')
    if system_type == 'Windows':
        ProcessFunc = ExportPutty
        f.write('@ECHO OFF\n')
        f.write('SET PUTTY=plink.exe\n')
    elif system_type == 'Linux':
        ProcessFunc = ExportAutoSSH
        f.write('#!/bin/bash\n')

    for classtype in ssh_issus:
        try:
            issus = classtype()
            # print issus.url
            html_content = spider.GetContent( issus )

            DEBUG = 1
            if DEBUG == 1:
                df = open(file_name, 'wb')
                if issus.coding == None :
                    df.write( html_content )
                else:
                    df.write( html_content.encode(issus.coding) )
                df.flush()
                df.close()

            if len(html_content) <> 0 :
                results = issus.parse( html_content )
                if results == None :
                    continue
                for result in results :
                    print result
                    cmdline = ProcessFunc(  result['host'],
                            result['port'],
                            result['username'],
                            result['password'] )
                    print cmdline
                    f.write( cmdline.encode('utf-8')+'\n' )
                    # raise 0
        finally:
            # print '-' * 30
            pass
    f.flush()
    f.close()
    if system_type == 'Linux':
        os.chmod( script_name, stat.S_IRWXU )
    print 'Please run : %s'%(script_name)
    print '*' * 50

